﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using XRGLib;
using Console = XRGLib.Console;
using Microsoft.Xna.Framework.Input;

namespace Examples
{
    class Example3 : ExampleBase
    {
        BSPTree bsp;
        int minHSize = 4;
        int minVSize = 4;
        float maxVRatio = 1f;
        float maxHRatio = 1f;

        int currLevel = 6;

        Surface menuSurface;

        public Example3(Console console, int width, int height, Game game)
            : base(console, width, height, game)
        {
            menuSurface = console.CreateSurface(28, 6);
            MakeTree();
        }

        public override string Description
        {
            get { return "Binary Space Partition"; }
        }

        public override void OnKeyboard(KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Space:
                    MakeTree();
                    break;

                case Keys.Add:
                    currLevel++;
                    MakeTree();
                    break;

                case Keys.Subtract:
                    currLevel--;
                    if (currLevel < 0)
                        currLevel = 0;
                    MakeTree();
                    break;

            }
        }

        public override Surface ReDraw()
        {
            surface.Clear();
            foreach (var n in bsp.GetAllLeaves())
            {
                surface.DrawFrame(n.Rect, null, false, ColorHelper.CreateFromPackedInt(0xffAA22), Color.Black);
            }
            DrawMenu();
            console.BlitAlpha(menuSurface, surface, menuSurface.Rect, 
                (surface.Width - menuSurface.Width)/2, 
                surface.Height - menuSurface.Height - 1,
                0.9f);
            return base.ReDraw();
        }

        void MakeTree()
        {
            bsp = new BSPTree(this.surface.Rect);
            bsp.SplitRecursive(currLevel, minHSize, minVSize, maxHRatio, maxVRatio, rand);

        }

        void DrawMenu()
        {
            menuSurface.DefaultBackground = Color.Beige;
            menuSurface.DefaultForeground = Color.Black;

            menuSurface.DrawFrame(menuSurface.Rect, null, true);

            menuSurface.PrintString(1, 1, "[+] Increase BSP Depth");
            menuSurface.PrintString(1, 2, "[-] Decrease BSP Depth");
            menuSurface.PrintString(1, 3, "[SPACE] New Random Tree");
            menuSurface.PrintString(1, 4, string.Format("Depth = {0}, Leaves = {1}", currLevel, bsp.GetAllLeaves().Count()));
        }
    }
}